<!-- 费用审核 系统级的，即一级路由标题栏-->
<template>
  <page-header-wrapper>
    <a-card id="a" :bordered="false">
      <!-- tab 切换日志 start -->
      <a-tabs @change="handleTab">
        <a-tab-pane :tab="list.desc" v-for="list in statusList" :key="list.value"> </a-tab-pane>
      </a-tabs>
      <!-- tab 切换日志  end -->
      <div>
        <s-table
          ref="table"
          size="default"
          :rowKey="record => record.id"
          bordered
          :columns="columns"
          :data="loadData"
          @change="handleTableChange(a, b, c)"
        >
          <template slot="title">
            <a-descriptions title="费用审核"></a-descriptions>
            <div class="table-page-search-wrapper">
              <a-form layout="inline">
                <a-row :gutter="48">
                  <a-col :md="8" :sm="24">
                    <a-form-item label="申请单号">
                      <a-input v-model="queryParam.applyNo" placeholder="请输入" />
                    </a-form-item>
                  </a-col>
                  <a-col :md="8" :sm="24">
                    <a-form-item label="申请类型">
                      <a-select v-model="queryParam.type" placeholder="请选择" default-value="0" allowClear>
                        <a-select-option
                          v-for="item in $const.SUBJECTANDREESA"
                          :key="item.value"
                          :value="item.value"
                        >
                          {{ item.desc }}
                        </a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <template v-if="advanced">
                    <a-col :md="8" :sm="24">
                      <a-form-item label="申请者ID">
                        <a-input v-model="queryParam.createUserNo" placeholder="请输入" />
                      </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                      <a-form-item label="收款人编号">
                        <a-input v-model="queryParam.userNo" placeholder="请输入" />
                      </a-form-item>
                    </a-col>
                    <a-col :md="8" :sm="24">
                      <a-form-model-item label="发起日期:" labelAlign="left">
                        <a-range-picker @change="handleSelectDate" v-model="queryDate" />
                      </a-form-model-item>
                    </a-col>
                  </template>
                  <a-col :md="(!advanced && 6) || 8" :sm="24">
                    <span
                      class="table-page-search-submitButtons"
                      :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
                    >
                      <a-button type="primary" @click="searchTable">查询</a-button>
                      <a-button style="margin-left: 8px" @click="reset">重置</a-button>
                      <a-button style="margin-left: 8px" type="button" icon="download" @click="clickExport" v-if="$auth('FEE_REVIEW.FEE_REVIEW_EXPORT')">导出</a-button>
                      <a @click="toggleAdvanced" style="margin-left: 8px">
                        {{ advanced ? '收起' : '展开' }}
                        <a-icon :type="advanced ? 'up' : 'down'" />
                      </a>
                    </span>
                  </a-col>
                </a-row>
              </a-form>
            </div>
          </template>
          <template slot="createTime" slot-scope="text, record">
            <span v-if="record.createTime">{{ record.createTime | moment() }}</span>
          </template>
          <template slot="totalAmount" slot-scope="text, record">
            <span >{{ record.totalAmount | formatAmount }}</span>
          </template>
          <template slot="type" slot-scope="text, record">
            {{ record.type == 1 ? '研究者' : '受试者' }}
          </template>
          <template slot="proId" slot-scope="text, record">
            <!-- {{ record.type == 1 ? '研究者' : '受试者' }} -->
            <a @click="switchToProject(record)">{{ record.proId }}</a>
          </template>
          <template slot="payTime" slot-scope="text, record">
            <span v-if="record.payTime">{{ record.payTime | moment() }}</span>
          </template>
          <template slot="status" slot-scope="text, record">
            {{ record.status | enumValueByKey($const.EXAMINE_TYPE) }}
          </template>
          <template slot="operation" slot-scope="text, record">
            <a @click="clickView(record)" v-if="$auth('FEE_REVIEW.FEE_REVIEW_DETAIL')">查看</a>
          </template>
          <template slot="userNo" slot-scope="text, record">
            <span>{{ record.type == $const.SUBJECTANDREESA.DAISHENGPI.value ? record.researchDetailNo : record.ptsNo }}</span>
          </template>
        </s-table>
        <DetailView
          @refresh="$refs.table.refresh()"
          @closeCallback="closeCallback"
          @openPopup="openPopup"
          @payRecord="payRecord"
          ref="detailView"
          :visible="visible"
          :info="{ name: 'xiaopang' }"
          :costId="costId"
          :thisStatus="thisStatus"
        ></DetailView>
        <AuditFailure
          :visible="visibles"
          @uploadModalCancel="uploadModalCancel"
          @uploadClickConfirm="uploadClickConfirm"
          :auditStatus="auditStatus"
          ref="AuditFailure"
        >
        </AuditFailure>
        <Approve
          :oveVisibles="oveVisibles"
          @uploadModalCancel="uploadModalCancel"
          :auditStatus="auditStatus"
          @roveModalCancel="roveModalCancel"
          ref="Approve"
        >
        </Approve>
      </div>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { auditList, switchAudit, applyTax, costRecordPay, getCostExport } from '@/api/cost/audit'
import DetailView from '@/views/cost-auditing/detail.vue'
import AuditFailure from '@/views/cost-auditing/components/auditFailure'
import Approve from '@/views/cost-auditing/components/approve'
import { exportExcel } from '@/utils/util'
import { buildPaginationObj } from '@/components/Table'
import { FINANCE_STATUS } from '@/constants/common'

export default {
  components: {
    DetailView,
    AuditFailure,
    Approve
  },
  data () {
    return {
      statusIndex: 1,
      statusList: FINANCE_STATUS,
      visible: false,
      visibles: false,
      oveVisibles: false,
      detailInfo: {},
      queryParam: {
        status: FINANCE_STATUS[0].value
      },
      costId: 0,
      queryDate: [],
      loadData: parameter => {
        if (this.$auth('FEE_REVIEW.FEE_REVIEW_LIST')) {
          return auditList(Object.assign(parameter, this.queryParam))
          .then(res => {
            this.pageSize = res.totalCount
            console.log(res, '*************')
            return res
          })
          .catch(() => { })
        } else {
          return Promise.resolve(buildPaginationObj([]))
        }
      },
      advanced: false,
      thisStatus: '',
      columns: [
        {
          title: '申请单号',
          key: 'applyNo',
          sorter: true,
          dataIndex: 'applyNo'
        },
        {
          title: '申请时间',
          key: 'createTime',
          sorter: true,
          dataIndex: 'createTime',
          scopedSlots: { customRender: 'createTime' }
        },
        {
          title: '付款类型',
          key: 'type',
          sorter: true,
          dataIndex: 'type',
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '申请者ID',
          key: 'createrId',
          dataIndex: 'createrId'
        },
        {
          title: '收款者编号',
          key: 'userNo',
          dataIndex: 'userNo',
          scopedSlots: { customRender: 'userNo' }
        },
        {
          title: '项目ID',
          key: 'proId',
          sorter: true,
          dataIndex: 'proId',
          scopedSlots: { customRender: 'proId' }
        },
        {
          title: '申请金额',
          key: 'totalAmount',
          sorter: true,
          dataIndex: 'totalAmount',
          scopedSlots: { customRender: 'totalAmount' }
        },
        {
          title: '付款时间',
          key: 'payTime',
          sorter: true,
          dataIndex: 'payTime',
          scopedSlots: { customRender: 'payTime' }
        },
        {
          title: '付款单号',
          key: 'payNo',
          sorter: true,
          dataIndex: 'payNo',
          scopedSlots: { customRender: 'payNo' }
        },
        {
          title: '当前状态',
          key: 'status',
          sorter: true,
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' }
        },

        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      pageSize: null,
      auditStatus: {}, // 审核弹窗审核状态
      preRecord: {} // 当前查看对象
    }
  },
  mounted () {
    // this.fetchList()
  },
  methods: {
    // 排序
    handleTableChange (pagination, filters, sorter) {
      console.log(12345679)
      if (sorter) {
        console.log(sorter, 'sorter')
      } else {
        console.log('打印')
      }
    },
    // 用于切换tab状态的
    handleTab (key) {
      this.statusIndex = key
      this.queryParam.status = key
      this.$refs.table.refresh(true)
      console.log(key)
    },
    clickExport () {
      const exportParams = this.queryParam
      exportParams.pageSize = this.pageSize
      // const exportParams = { proId: 393, status: 30 }
      getCostExport(exportParams).then(res => {
        exportExcel('费用审核', res)
      })
    },
    // 点击展开 详细搜索信息
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    // 点击重置
    reset () {
      if (this.queryParam.status) {
        this.queryParam = {
          status: this.queryParam.status
        }
      } else {
        this.queryParam = {}
      }
      this.queryDate = []
      this.$refs.table.refresh(true)
    },
    // 点击项目id跳转到项目详情
    switchToProject (record) {
      if (this.$options.filters.isHasAuth(this.$const.ROLE_TYPE.FINANCE.value)) {
        this.$router.push({ name: 'Treasure', query: { id: record.proId } })
        } else {
        this.$router.push({ name: 'Responsible', query: { id: record.proId } })
      }
    },
    // 点击查看
    clickView (record) {
        this.preRecord = record
        this.costId = record.id
        this.thisStatus = record.status
        // alert(this.thisStatus)
        this.visible = true
    },
    clickEdit (record) {
      console.log('点击编辑', record)
      // this.$router.push({ name: 'EditResearcher', query: { ...record } })
    },
    // 处理发起日期选择框改变时产生的回调
    handleSelectDate (date, dateString) {
      this.queryDate = date
      this.queryParam.applyStartTime = dateString[0]
      this.queryParam.applyEndTime = dateString[1]
      console.log(date, dateString, '打印Date')
    },
    searchTable () {
      // this.loadData(this.queryParam)
      this.$refs.table.refresh(true)
    },
    // 弹窗关闭回调
    closeCallback () {
      this.visible = false
    },
    // 审核弹窗关闭回调
    uploadModalCancel () {
      this.visibles = false
      this.oveVisibles = false
    },
    // 审核弹窗确认回调
    uploadClickConfirm (value) {
      const status = value.status === true ? 1 : -1
      this.$refs.AuditFailure.confirmLoading = true
      switchAudit({ id: value.id, status: status, refuseReason: value.refuseReason })
      .then(res => {
        this.$refs.AuditFailure.confirmLoading = false
        this.$refs.AuditFailure.form = {}
        this.$message.success('操作成功')
        this.uploadModalCancel()
        this.closeCallback()
        this.$refs.table.refresh()
      })
      .catch(() => {
        this.$refs.AuditFailure.confirmLoading = false
      })
    },
    // 打开审核弹窗
    openPopup (value) {
      if (value.status === 1) {
        // debugger
        this.auditStatus = value
        this.oveVisibles = true
        return
      }
      this.auditStatus = value
      this.visibles = true
    },
    // 个税凭证确认
    roveModalCancel (value) {
      if (value.personalTax > this.preRecord.totalAmount) {
        this.$message.error('申报金额不能大于费用申请金额')
        return
      }
      this.$refs.Approve.confirmLoading = true
      applyTax({ ...value })
      .then(res => {
        this.$message.success('操作成功')
        this.$refs.Approve.confirmLoading = false
        this.uploadModalCancel()
        this.closeCallback()
        this.$refs.table.refresh()
      })
      .catch(() => {
        this.$refs.Approve.confirmLoading = false
      })
    },
    payRecord () {
      this.$refs.detailView.payLoading = true
      costRecordPay({ id: this.costId }).then(res => {
        this.$refs.detailView.payLoading = false
        this.$message.success('操作成功')
        this.closeCallback()
        this.uploadModalCancel()
        this.$refs.table.refresh()
      }).catch(_ => {
        this.$refs.detailView.payLoading = false
      })
    }
  }
}
</script>
